package com.hnbtr.web.interceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.hnbtr.pojo.Manager;

public class LoginStatusInterceptor implements HandlerInterceptor {

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		Manager manager = (Manager) request.getSession().getAttribute("manager");
		if(manager != null) {
			return true;
		}
		String passport = request.getHeader("passport");
		if(passport != null && !passport.equals("")) {
			return true;
		}
		Cookie[] cookies = request.getCookies();
		if(cookies != null) {
			for(Cookie cookie : cookies) {
				if(cookie.getName().equals("passport")) {
					if(cookie.getValue() != null && !cookie.getValue().equals("")) {
						return true;
					}
				}
			}
		}
		request.getRequestDispatcher("/manager/timeout").forward(request, response);
		return false;
	}
	
}
